//
//  HWfySxGeneratingResultViewController.swiftOLaoNt
//  QRScan
//
//  Created by Qiang on 2018/3/26.
//  Copyright © 2018年 Qiang. All rights reserved.
//

import UIKit
import Photos

class HWfySxGeneratingResultViewController: JGayoKJCBaseViewController,UIImagePickerControllerDelegate,UINavigationControllerDelegate {

    @IBOutlet weak var colorButton: UIButton!
    @IBOutlet weak var imageView: UIImageView!
    
    fileprivate var pickColorV:YmSidVPickColorView = {
        let view = YmSidVPickColorView()
        view.clipsToBounds = true
        view.backgroundColor = UIColor.clear
        return view
    }()
    
    var qrString = ""
    var qrImage = UIImage()
    var qrColor = UIColor.black
    
    var isAddLogoImage = false
    
    private var logoimage:UIImage!
    private var backGroungImg:UIImage!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.title = "QR image"
        self.imageView.image = self.qrImage
        self.imageView.tintColor = UIColor.red
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "save", style: .plain, target: self, action: #selector(saveToAlbum))
        self.pickColorV.frame = CGRect(x: 10, y: SCREEN_HEIGHT-64-150, width: 300, height: 150)
        self.view.addSubview(self.pickColorV)
        self.pickColorV.setupSubView()
        self.pickColorV.frame = CGRect(x: 50, y: SCREEN_HEIGHT-64, width: 0, height: 0)
        self.pickColorV.buttonClick = {(index) in
            self.addColor(index: index)
            UIView.animate(withDuration: 0.3, animations: {
                self.pickColorV.frame = CGRect(x: 50, y: SCREEN_HEIGHT-64, width: 0, height: 0)
                self.colorButton.isSelected = false
            })

        }
        // Do any additional setup after loading the view.
    }
 
    private func addColor(index:NSInteger){
        let colors = [UIColor.lightGray,UIColor.gray,UIColor.darkGray,colorWithRGB(245, g: 166, b: 189, a: 1),UIColor.blue,UIColor.brown,colorWithRGB(58, g: 181, b: 175, a: 1),UIColor.red,colorWithRGB(59, g: 181, b: 84, a: 1),colorWithRGB(211, g: 210, b: 135, a: 1),UIColor.purple,UIColor.magenta,colorWithRGB(220, g: 240, b: 79, a: 1),colorWithRGB(100, g: 148, b: 181, a: 1),colorWithRGB(40, g: 176, b: 255, a: 1),colorWithRGB(255, g: 161, b: 46, a: 1),colorWithRGB(211, g: 178, b: 255, a: 1),colorWithRGB(152, g: 184, b: 185, a: 1)][index-1]
        self.qrColor = colors
        var img = self.createQRScanImage(content: self.qrString,bgColor: UIColor.white ,size:CGSize(width: 300, height: 300), color: colors)
        
        if self.backGroungImg != nil {
            img = self.createQRScanImage(content: self.qrString, bgColor: UIColor.clear, size: CGSize(width: 300, height: 300), color: UIColor.red)
            img = self.addBackGroundImage(image: img, bgImage: self.backGroungImg)
        }
        
        if self.logoimage != nil {
            self.imageView.image = self.addIconToQRScanImage(image: img, icon: self.logoimage, iconSize: CGSize(width: 60, height: 60))
        }else{
            self.imageView.image = img
        }
    }
    
    @IBAction func colorButtonClick(_ sender: Any) {
        if let button = sender as? UIButton {
            if button.isSelected {
                UIView.animate(withDuration: 0.3, animations: {
                    self.pickColorV.frame = CGRect(x: 50, y: SCREEN_HEIGHT-64, width: 0, height: 0)
                })
            }else{
                UIView.animate(withDuration: 0.3, animations: {
                    self.pickColorV.frame = CGRect(x: 10, y: SCREEN_HEIGHT-64-150, width: 300, height: 150)
                })
            }
            
            button.isSelected = !button.isSelected
        }
        
      
    }
    private func createQRScanImage(content:String,bgColor:UIColor,size:CGSize,color:UIColor)->UIImage{
        let stringData = content.data(using: String.Encoding.utf8)
        let qrFilter = CIFilter(name: "CIQRScanGenerator")
        
        qrFilter?.setValue(stringData, forKey: "inputMessage")
        qrFilter?.setValue("H", forKey: "inputCorrectionLevel")
        
        let colorFilter = CIFilter(name: "CIFalseColor")
        colorFilter?.setDefaults()
        
        colorFilter?.setValuesForKeys(["inputImage" : (qrFilter?.outputImage)!,"inputColor0":CIColor.init(cgColor: color.cgColor),"inputColor1":CIColor.init(cgColor: bgColor.cgColor)])
        
        let qrImage = colorFilter?.outputImage
        let cgImage = CIContext(options: nil).createCGImage(qrImage!, from: (qrImage?.extent)!)
        UIGraphicsBeginImageContext(size)
        let context = UIGraphicsGetCurrentContext()
        context!.interpolationQuality = .none
        context!.scaleBy(x: 1.0, y: -1.0)
        context?.draw(cgImage!, in: (context?.boundingBoxOfClipPath)!)
        let codeImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return codeImage!
    }
    
    
    
    
    @IBAction func addLogoClick(_ sender: Any) {
        self.isAddLogoImage = true
        self.pickPicture()
    }
    
    @IBAction func addBGimage(_ sender: Any) {
        self.isAddLogoImage = false
        self.pickPicture()
    }
    @objc func pickPicture(){
        if PhotoLibraryPermissions() {
            let picker = UIImagePickerController()
            //设置代理
            picker.delegate = self
            //指定图片控制器类型
            picker.sourceType = UIImagePickerControllerSourceType.photoLibrary
            //弹出控制器，显示界面
            self.present(picker, animated: true, completion: {
                () -> Void in
            })
        }
        
    }
    
    private func PhotoLibraryPermissions() -> Bool {
        
        let library:PHAuthorizationStatus = PHPhotoLibrary.authorizationStatus()
        if library == PHAuthorizationStatus.notDetermined{
            PHPhotoLibrary.requestAuthorization({ (libraryStatus) in
                
            })
        }
        if(library == PHAuthorizationStatus.denied || library == PHAuthorizationStatus.restricted){
            showAlert("alert", message: "please check your permission settings: Settings> Privacy> Camera", VC: self)
            return false
        }else {
            return true
        }
    }
    
    //图片选择代理
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        //获取选择的原图
        let image = info[UIImagePickerControllerOriginalImage] as! UIImage
        
        picker.dismiss(animated: false, completion: {
            () -> Void in
            
        })
        
        let cropVC:AKxXjaJCImageCropViewController = AKxXjaJCImageCropViewController()
        cropVC.initWithImage(image, complentBlock: { (str,images) in
            if self.isAddLogoImage {
                self.logoimage = images
                self.imageView.image = self.addIconToQRScanImage(image: self.imageView.image!, icon: images, iconSize: CGSize(width: 60, height: 60))
            }else{
                self.backGroungImg = images
                let img = self.createQRScanImage(content: self.qrString,bgColor:  UIColor.clear,size:CGSize(width: 300, height: 300), color:self.qrColor)
                let bgImage = self.addBackGroundImage(image: img, bgImage: images)
                
                if self.logoimage != nil {
                    self.imageView.image = self.addIconToQRScanImage(image: bgImage, icon: self.logoimage, iconSize: CGSize(width: 60, height: 60))
                }else{
                    self.imageView.image = bgImage
                }
            }
            
        }) { () in
            
        }
        
        self.present(cropVC, animated: true, completion: nil)
    }
    
    // MARK:----向二维码中添加图片
    private func addIconToQRScanImage(image:UIImage,icon:UIImage,iconSize:CGSize)->UIImage{
        UIGraphicsBeginImageContext(image.size)
        
        let imageWidth = image.size.width
        let imageHeight = image.size.height
        let iconWidth = iconSize.width
        let iconHeight = iconSize.height
        image.draw(in: CGRect(x: 0, y: 0, width: imageWidth, height: imageHeight))
        icon.draw(in: CGRect(x: (imageWidth-iconWidth)/2.0, y: (imageHeight-iconHeight)/2.0, width: iconWidth, height: iconHeight))
        let qrImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        
        return qrImage!
    }
    
    private func addBackGroundImage(image:UIImage,bgImage:UIImage)->UIImage{
        UIGraphicsBeginImageContext(image.size)
        
        let imageWidth = image.size.width
        let imageHeight = image.size.height
        
        bgImage.draw(in: CGRect(x: 0, y: 0, width: imageWidth, height: imageHeight))
        image.draw(in: CGRect(x: 0, y: 0, width: imageWidth, height: imageHeight))
        let qrImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        
        return qrImage!
    }
    
    @objc private func saveToAlbum(){
        UIImageWriteToSavedPhotosAlbum(self.imageView.image!, self, #selector(image(image:didFinishSavingWithError:contextInfo:)), nil)
        
    }
    @objc func image(image:UIImage,didFinishSavingWithError error:NSError?,contextInfo:AnyObject) {
        if error == nil
        {
            showAlert("success", message: "The picture has been saved to the album", VC: self)
            
        }else{
           showAlert("failed", message: "Save failure", VC: self)
        }
        
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
